package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/12.<br><br>
 *
 * 反转链表
 */
public class Topic206 {
    public static void main(String[] args) {
        Topic206 instance = new Topic206();

        int[] array = new int[] {1,2,3,4,5};
        ListNode head = Util.createList(array);
        Util.printList(instance.reverseList(head));
    }

    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode newHead = null;
        ListNode temp;

        while (head != null) {
            temp = head;

            head = head.next;

            temp.next = newHead;
            newHead = temp;
        }

        return newHead;
    }

    public ListNode reverseList3(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode node = head.next;
        head.next = null;

        ListNode temp;
        while (node != null) {
            temp = node.next;
            node.next = head;
            head = node;
            node = temp;
        }

        return head;
    }

    public ListNode reverseList2(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;

        return newHead;
    }
}
